package com.ft.adbix.core.view.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.ft.adbix.core.R;
import com.ft.adbix.core.ad.manager.InterstitialAdManager;
import com.ft.adbix.core.ad.manager.RewardAdManager;
import com.ft.adbix.core.base.BaseActivity;
import com.ft.adbix.core.listener.CusClickListener;
import com.ft.adbix.core.listener.InterstitialListener;
import com.ft.adbix.core.response.Ad;
import com.ft.adbix.core.response.AppPromotion;
import com.ft.adbix.core.response.Video;
import com.ft.adbix.core.view.dialog.RewardDetentionDialog;
import com.ft.adbix.core.widget.roundedimageview.RoundedImageView;
import com.ft.adbix.utils.AdLogUtils;
import com.ft.adbix.utils.AdOpener;
import com.ft.adbix.utils.AdTrackerReporter;
import com.ft.adbix.utils.universalimageloader.core.ImageLoader;

public class FullScreenVideoActivity extends BaseActivity {

    private static String AD_REQ_ID = "ad_req_id";
    private String currentReqId = "";
    Ad adData;
    InterstitialListener interstitialListener;
    RelativeLayout layoutVideo;
    RelativeLayout layoutParent;
    VideoView videoView;
    private Video videoInfo;
    private ImageView ivSkip;
    private TextView tvCountDown;
    private ProgressBar progressBar;
    //单位秒
    private int currentDuration;
    private Handler handler = new Handler();
    private ImageView ivMute;
    private Runnable videoProgressTask;
    private AdTrackerReporter reporter;
    private AdOpener adOpener;
    private boolean isMute = false;
    private MediaPlayer mediaPlayer;
    private String countdownFormat;
    private boolean complete;

    public static void start(Context context, String reqId) {
        Intent starter = new Intent(context, FullScreenVideoActivity.class);
        starter.putExtra(AD_REQ_ID, reqId);
        context.startActivity(starter);
    }

    @Override
    public boolean isFullScreen() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_reward_video;
    }

    @Override
    public void initView() {
        layoutVideo = findViewById(R.id.adbix_lib_rl_video_container);
        layoutParent = findViewById(R.id.adbix_lib_reward_video_rl_parent);
        ivMute = findViewById(R.id.adbix_lib_iv_mute);
        ivSkip = findViewById(R.id.adbix_lib_iv_skip);
        tvCountDown = findViewById(R.id.adbix_lib_tv_count_down);
        progressBar = findViewById(R.id.adbix_lib_progress_bar);
//        ivSkip.setVisibility(View.GONE);
        setListener();
        loadInterstitialAd();

        if (adData == null) {
            finish();
            return;
        }
        AdLogUtils.d("interstitialAdInfo = "+adData.toString());
        interstitialListener = InterstitialAdManager.getInstance().getInterstitialListener(currentReqId);
        videoInfo = adData.getVideo();
        reporter = new AdTrackerReporter(adData);
        adOpener = new AdOpener(this, adData, reporter);
        initVideo();
        initActionView();
    }

    private void initActionView() {
//        if (adData.getActionType() == 3) {
        AppPromotion appPromotion = adData.getAppPromotion();
        if (appPromotion==null){
            return;
        }
        View actionView = LayoutInflater.from(this).inflate(R.layout.adbix_include_reward_vod_action_bar2, layoutParent, false);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        layoutParams.leftMargin = 20;
        layoutParams.rightMargin = 20;
        layoutParams.bottomMargin = 20;
        layoutParent.addView(actionView, layoutParams);
        RoundedImageView ivIcon = actionView.findViewById(R.id.adbix_actionbar_iv_image);
        ImageLoader.getInstance().displayImage(appPromotion.getAppIconUrl(), ivIcon);
        TextView tvTitle = actionView.findViewById(R.id.adbix_actionbar_tv_title);
        tvTitle.setText(adData.getTitle());
        TextView tvDesc = actionView.findViewById(R.id.adbix_actionbar_tv_desc);
        tvDesc.setText(adData.getDesc());
//        }
        if (interstitialListener != null) {
            interstitialListener.onAdShow();
        }

    }

    private void setListener() {
        ivMute.setOnClickListener(new CusClickListener() {
            @Override
            public void onSingleClick(View var1) {
                if (mediaPlayer == null) {
                    return;
                }
                if (isMute) {
                    isMute = false;
                    mediaPlayer.setVolume(1f, 1f);
                    reporter.reportVideoUnmute();
                } else {
                    isMute = true;
                    mediaPlayer.setVolume(0f, 0f);
                    reporter.reportVideoMute();
                }
                ivMute.setImageResource(isMute ? R.drawable.adbix_reward_mute : R.drawable.adbix_reward_voice);
            }
        });
        ivSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoInfo == null) {
                    return;
                }
                finish();
//                if (currentDuration < videoInfo.getForceDuration()) {
//                    showDetentionDialog();
//                }
            }
        });
    }

    private void loadInterstitialAd() {
        Intent intent = getIntent();
        currentReqId = intent.getStringExtra(AD_REQ_ID);

        AdLogUtils.d("fullscreen video currentReqId = "+currentReqId);
        adData = InterstitialAdManager.getInstance().getInterstitialAdData(currentReqId);

    }

    private void initVideo() {
        videoView = new VideoView(this);
        //设置播放完成以后监听
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                currentDuration = videoInfo.getDuration();
                complete = true;
                reporter.markPlayFinish(true);
                reporter.reportVideoEnd();
                handler.removeCallbacks(videoProgressTask);
                if (interstitialListener != null) {
                    interstitialListener.onVideoCompleted();
                }
            }
        });
        //设置发生错误监听，如果不设置videoview会向用户提示发生错误
        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                if (interstitialListener != null) {
                    interstitialListener.onVideoError();
                }
                reporter.reportVideoError();
                return false;
            }
        });
        //设置在视频文件在加载完毕以后的回调函数
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                int videoWidth = mp.getVideoWidth();
                int videoHeight = mp.getVideoHeight();
                float aspectRatio = (float) videoWidth / videoHeight;

                ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutParams.height = (int) (layoutParams.width / aspectRatio);
                videoView.setLayoutParams(layoutParams);
                progressBar.setVisibility(View.GONE);
                mp.start();
                mediaPlayer = mp;
                reporter.reportVideoLoaded();
                startVideo();

            }
        });

        //设置网络视频路径
//        Uri uri= Uri.parse("http://123.150.52.227/0725695b00000000-1415769042-1960016430/data5/vkplx.video.qq.com/flv/74/164/a0015193bxf.p203.1.mp4");
        Uri uri = Uri.parse(videoInfo.getUrl());
        videoView.setVideoURI(uri);
        //设置为全屏模式播放
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        //设置相对于父布局四边对齐
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        //为VideoView添加属性
//        videoView.setLayoutParams(layoutParams);
        layoutVideo.addView(videoView, layoutParams);
        View touchView = new View(this);
        //设置videoView的点击监听
        touchView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AdLogUtils.d("touch = " + event.getAction());
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        reporter.markDown(event.getX(), event.getY(), event.getRawX(), event.getRawY());
                        break;
                    case MotionEvent.ACTION_UP:
                        reporter.markUp(event.getX(), event.getY(), event.getRawX(), event.getRawY());
                        reporter.reportClick();
                        adOpener.openAd();
                        interstitialListener.onAdClick();
                        break;
                }
                return true;
            }
        });
        layoutVideo.addView(touchView,layoutParams);

        reporter.reportDisplay();
    }

    private void startVideo() {
        reporter.reportVideoStart();
        if (videoInfo.getForceDuration() > 0) {
            tvCountDown.setVisibility(View.VISIBLE);
            countdownFormat = getResources().getString(R.string.adbix_reward_achieve_count_down);
            tvCountDown.setText(String.format(countdownFormat, videoInfo.getForceDuration()));
        }
        if (videoProgressTask == null) {
            videoProgressTask = new Runnable() {
                @Override
                public void run() {
                    currentDuration = videoView.getCurrentPosition() / 1000;
                    reporter.markPlayDuration(currentDuration);
                    if (currentDuration >= videoView.getDuration()) {
                        handler.removeCallbacks(videoProgressTask);
                        return;
                    }
                    int forceCountDown = (videoInfo.getForceDuration() - currentDuration);
                    if (forceCountDown > 0) {
                        tvCountDown.setText(String.format(countdownFormat, forceCountDown));
                    } else {
                        tvCountDown.setText("奖励已获得");
                    }
                    //播放四分一
                    if (currentDuration == videoInfo.getDuration() / 4) {
                        reporter.reportVideoQuarter();
                    }
                    //播放一半
                    if (currentDuration == videoInfo.getDuration() / 2) {
                        reporter.reportVideoMiddle();
                    }
                    //播放四分三
                    if (currentDuration == videoInfo.getDuration() * 3 / 4) {
                        reporter.reportVideoThirdQuarter();
                    }
//                    //激励成功
//                    if (currentDuration >= videoInfo.getForceDuration() && !hasReward) {
//                        hasReward = true;
//                        reporter.reportRewardSuccess();
//                        interstitialListener.onAdReward();
//                    }
                    handler.postDelayed(this, 1000);
                }
            };
        }
        handler.post(videoProgressTask);
    }

    @Override
    protected void onDestroy() {
        if (interstitialListener != null) {
            interstitialListener.onAdClose();
        }
        if(videoView!=null){
            videoView.stopPlayback();
        }
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pauseVideo();
    }

    private void pauseVideo() {
        if (videoView != null && videoInfo != null && videoView.isPlaying()) {
            handler.removeCallbacks(videoProgressTask);
            videoView.pause();
            AdLogUtils.d("resume currentDuration = " + currentDuration);
            reporter.reportVideoPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        resumeVideo();
    }

    private void resumeVideo() {
        if (videoView != null && videoInfo != null && !videoView.isPlaying()) {
            AdLogUtils.d("resume currentDuration = " + currentDuration);
            if (!complete) {
                videoView.start();
                videoView.seekTo(currentDuration * 1000);
                handler.post(videoProgressTask);
                reporter.reportVideoResume();
            }
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        showDetentionDialog();
    }

    private void showDetentionDialog() {
        pauseVideo();
        RewardDetentionDialog dialog = new RewardDetentionDialog(this, adData, new RewardDetentionDialog.OnOperateListener() {
            @Override
            public void onFinishAd() {
                reporter.reportVideoClose();
                RewardAdManager.getInstance().removeReward(currentReqId);
                finish();
            }

            @Override
            public void onResumeAd() {
                resumeVideo();
            }

            @Override
            public void onDownload() {
                if ("1".equals(adData.getDownloadType())) {
                    adOpener.gotoAppStore();
                } else {
                    adOpener.openAd();
                }
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                resumeVideo();
            }
        });
        dialog.show();
    }
}